package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.config.MyInterceptor;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor poolExecutor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 返回订单确认页需要的数据（防重令牌）
     * <p>
     * Feign远程调用丢失请求头问题：
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //获取当前线程-->主线程的RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1、异步：远程调用->用户服务，根据用户Id查询该用户的收货地址
        CompletableFuture<Void> addressThread = CompletableFuture.runAsync(() -> {
            //在新线程内，远程调用之前，将主线程的RequestAttributes拷贝一份。
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddressById(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        }, poolExecutor);

        //2、异步：远程调用->购物车服务，获取用户购物车中所有已选中的购物项
        CompletableFuture<Void> itemsThread = CompletableFuture.runAsync(() -> {
            //在新线程内，远程调用之前，将主线程的RequestAttributes拷贝一份。
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.currentUserCartItems();
            orderConfirmVo.setItems(items);
        }, poolExecutor).thenRunAsync(() -> {
            //3 异步：远程调用->购物车服务，查询所有购物项的有货无货状态
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> ids = items.stream().map((item) -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            R r = wmsFeignService.getSkuHasStock(ids);
            List<SkuHasStockTo> data = r.getData(new TypeReference<List<SkuHasStockTo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> collect = data.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                orderConfirmVo.setStocks(collect);
            }
        }, poolExecutor);

        //4、优惠信息，用户积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //等待两个线程都完成
        CompletableFuture.allOf(addressThread, itemsThread).get();

        //5、防重令牌Token
        //5.1、生成一个Token令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //5.2、页面保存一份token
        orderConfirmVo.setOrderToken(token);
        //5.3、服务器保存一份（redis保存）
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);

        return orderConfirmVo;
    }

    /**
     * 下单功能：生成订单
     *
     * @param vo
     * @return
     */
    //本地事务，在分布式系统下，只能控制自己的回滚，控制不了其他服务的回滚
//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        response.setCode(0);
        confirmVoThreadLocal.set(vo);
        //下单:验令牌，验价格，锁库存
        //1、验证令牌【令牌的对比和删除必须保证原子性】
        //0令牌失败 1删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1])else return 0 end";
        String orderToken = vo.getOrderToken();
        //lua脚本：原子验证token令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0L) {
            //令牌验证失败
            response.setCode(1);
            return response;
        } else {
            //令牌验证成功
            //1、创建订单、订单项信息
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPeice = vo.getPayPrice();
            //金额对比
            if (Math.abs(payAmount.subtract(payPeice).doubleValue()) < 0.01) {
                //TODO 3、保存订单
                saveOrder(order);
                //TODO 4、库存锁定。
                //订单号 订单项：skuId skuName num
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map((item) -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(locks);
                //远程调用->库存服务，锁定库存
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁成功
                    response.setOrder(order.getOrder());

                    //TODO 5、远程调用->会员系统，扣减积分
//                    int i = 10/0;//模拟远程调用出问题的情况

                    //TODO 订单创建成功后，给MQ发送消息，记录该信息
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return response;
                } else {
                    //锁失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                response.setCode(2);
                return response;
            }
        }
//        String redieToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_PREFIX + memberRespVo.getId());
//        if (orderToken!=null&&orderToken.equals(redieToken)){
//            //令牌匹配
//            return response;
//        }else {
//            //令牌不匹配
//            return response;
//        }
    }

    /**
     * 查询：根据订单号，返回订单状态
     *
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderStatusBySn(String orderSn) {
        OrderEntity entity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return entity;
    }

    /**
     * 关闭订单：自动关闭过期且没有支付的订单
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态status
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity != null && orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {//如果还没有支付，则关闭订单
            //关闭订单
            OrderEntity entity1 = new OrderEntity();
            entity1.setId(entity.getId());
            entity1.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(entity1);

            //再个给MQ发送一条，确保库存解锁成功
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity, orderTo);
            try {
                //TODO 保证消息一定会发送出去，每一个消息都做好日志记录（给数据库保证每一个消息的详细信息）
                //TODO 定期扫描数据库将失败信息在发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception ex) {
                //TODO 重试，将没有发送出去的消息进行重新发送
            }
        }
    }

    /**
     * 构建当前订单的支付信息
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        //根据订单号获取订单实体
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);//小数位只取2位且向上取整（如：0.001->0.01 ）
        payVo.setTotal_amount(bigDecimal.toString());//订单金额
        payVo.setOut_trade_no(orderSn);//订单号

        List<OrderItemEntity> entities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = entities.get(0);
        payVo.setSubject(entity.getSkuName());//订单主体
        payVo.setBody(entity.getSkuAttrsVals());//订单备注
        return payVo;
    }

    /**
     * 分页查询：当前用户的订单列表
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        //1、获取当前登录用户的id
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        Long id = memberRespVo.getId();

        //分页查询
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",id).orderByDesc("id")
        );

        List<OrderEntity> list1 = page.getRecords().stream().map(item -> {
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", item.getOrderSn()));
            item.setItemEntityList(list);
            return item;
        }).collect(Collectors.toList());

        page.setRecords(list1);

        return new PageUtils(page);


    }

    /**
     * 处理支付宝的支付结果
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水信息
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);

        //2、修改订单状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功，修改订单状态
            String out_trade_no = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(out_trade_no,OrderStatusEnum.PAYED.getCode());
        }

        return "success";
    }

    /**
     * 为秒杀商品，快速保存订单
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal price = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(price);
        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(price);
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());
        //sku详细信息....
        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        //在使用seata0.7.1做分布式事务时，执行批量sql会有bug（seata0.8版本以上才支持批量操作）
        orderItemService.saveBatch(order.getOrderItems());
    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //构建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //2、获取到所有订单项
        List<OrderItemEntity> itemEntities = buildOrderItem(orderSn);

        //3、计算价格、积分等相关
        computePrice(orderEntity, itemEntities);

        OrderCreateTo createTo = new OrderCreateTo();
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单总额=每一个订单项的实际金额
        for (OrderItemEntity entity : itemEntities) {
            total = total.add(entity.getRealAmount());

            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());

            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //1、订单价格、积分等相关
        //订单总额
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        //设置积分信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        //删除状态
        orderEntity.setDeleteStatus(0);//未删除
    }

    /**
     * 构建订单
     *
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(LoginUserInterceptor.threadLocal.get().getId());
        entity.setMemberUsername(LoginUserInterceptor.threadLocal.get().getUsername());
        //设置运费
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        //远程调用->库存服务，计算运费
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getRegion());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());
        //设置订单状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setConfirmStatus(0);//新增++
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItem(String orderSn) {
        //远程调用->购物车服务，获取所有购物项
        List<OrderItemVo> cartItems = cartFeignService.currentUserCartItems();
        if (cartItems != null && cartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = cartItems.stream().map((item) -> {
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 根据某一个购物项，构建一个订单项
     *
     * @param cartVo
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartVo) {
        OrderItemEntity entity = new OrderItemEntity();
        //1、订单信息
        //2、spu信息
        Long skuId = cartVo.getSkuId();
        //远程调用->商品服务，获取spu信息
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        entity.setSpuId(data.getId());
        entity.setSpuBrand(data.getBrandId().toString());
        entity.setSpuName(data.getSpuName());
        entity.setCategoryId(data.getCatalogId());
        //3、sku信息
        entity.setSkuId(cartVo.getSkuId());
        entity.setSkuName(cartVo.getTitle());
        entity.setSkuPic(cartVo.getImage());
        entity.setSkuPrice(cartVo.getPrice());
        String s = StringUtils.collectionToDelimitedString(cartVo.getSkuAttr(), ";");
        entity.setSkuAttrsVals(s);
        entity.setSkuQuantity(cartVo.getCount());
        //4、优惠信息（不做）
        //5、积分信息
        entity.setGiftGrowth(cartVo.getPrice().multiply(new BigDecimal(cartVo.getCount())).intValue());
        entity.setGiftIntegration(cartVo.getPrice().multiply(new BigDecimal(cartVo.getCount())).intValue());
        //6、订单项的价格信息
        entity.setPromotionAmount(new BigDecimal("0"));
        entity.setCouponAmount(new BigDecimal("0"));
        entity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额：总额-各种优惠
        BigDecimal orign = entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(entity.getPromotionAmount())
                .subtract(entity.getCouponAmount())
                .subtract(entity.getIntegrationAmount());
        entity.setRealAmount(subtract);
        return entity;
    }


    /**
     * 通过 aspectj 解决：本类方法互相调用时事务失效问题。
     * 前提：①引入 aop-starter ②@EnableAspectJAutoProxy(exposeProxy = true)
     */
    @Transactional
    public void a() {
        //1、通过 aspectj 提供的 AopContext.currentProxy()方法，获取代理对象。
        //2、将 AopContext.currentProxy()方法返回的代理对象，强转为当前类的一个实例。
        OrderServiceImpl order = (OrderServiceImpl) AopContext.currentProxy();
        //3、通过这个代理对象，来调用本类的其他方法，解决：本类互调事务失效问题。
        order.b();
        order.c();
    }

    @Transactional
    public void b() {
    }

    @Transactional
    public void c() {
    }


}